package com.storydo.file.share.base.controller;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.storydo.file.share.base.entity.ResponseEntity;
import com.storydo.file.share.utils.Stringer;

/**
 * <strong>Title : BaseController </strong>. <br>
 * <strong>Description : 基本根Controller，所有子模块Controller均必须继承于它.</strong> <br>
 * <strong>Create on : Mar 16, 2016 4:41:48 PM </strong>. <br>
 * <p>
 * <strong>Copyright (C) YOX Internet Technology Co.,Ltd.</strong> <br>
 * </p>
 * 
 * @author k2 <br>
 * @version <strong>base-platform-0.1.0</strong> <br>
 *          <br>
 *          <strong>修改历史: .</strong> <br>
 *          修改人 修改日期 修改描述<br>
 *          -------------------------------------------<br>
 *          <br>
 *          <br>
 */
public class BaseController {

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected HttpServletResponse response;

	// 默认每页显示记录条数
	protected final static int DEFAULT_PAGE_SIZE = 10;

	/**
	 * @author by K2 Mar 23, 2016
	 *
	 * @desc 获取spring容器中的Bean.
	 * @param clazz
	 * @return
	 */
	// protected <T> T getBean(Class<T> clazz) {
	// return SpringContextHolder.getBean(clazz);
	// }

	/**
	 * @author by K2 Mar 23, 2016
	 *
	 * @desc 构造错误的返回信息（带errorCode）.
	 * @param errorCode
	 *            错误代码
	 * @param errorMessage
	 *            错误信息
	 * @return
	 * @throws Exception
	 */
	protected Object error(Integer errorCode, String errorMessage) {
		return new ResponseEntity(errorCode, errorMessage).toJson();
	}

	/**
	 * @author by K2 Mar 23, 2016
	 *
	 * @desc 构造错误的返回信息（不带errorCode）.
	 * @param errorMessage
	 *            错误信息
	 * @return
	 * @throws Exception
	 */
	protected Object error(String errorMessage) {
		return new ResponseEntity(null, errorMessage).toJson();
	}

	protected Object success() {
		return "{\"success\":true,\"data\":{}}";
	}
	
	/**
	 * @author by K2 Mar 23, 2016
	 *
	 * @desc 构造成功的返回信息.
	 * @param data
	 *            - 业务数据json
	 * @return
	 * @throws Exception
	 */
	protected Object success(Object data) {
		return new ResponseEntity(data).toJson();
	}

	/**
	 * 
	* @Description: 根据请求的参数生成一个指定的对象
	* @param cls
	* @return
	* @throws InstantiationException
	* @throws IllegalAccessException
	* @author: Storydo
	* @date: 2020年3月4日 下午6:31:30
	 */
	protected <T> T convertFromRequest(Class<T> cls) throws InstantiationException, IllegalAccessException {
		T obj = cls.newInstance();
		List<Class<?>> argsCls = Arrays.asList(String.class, Boolean.class, Integer.class, Long.class, Double.class, Float.class);
		PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(cls);
		for (PropertyDescriptor prop : props) {
			if (!argsCls.contains(prop.getPropertyType())) {
				continue;
			}
			Method setMethod = prop.getWriteMethod();
			String val = request.getParameter(prop.getDisplayName());
			if (!isNullOrEmpty(val) && setMethod != null) {
				try {
					Class<?> propCls = prop.getPropertyType();
					if (String.class.isAssignableFrom(propCls)) {						
						setMethod.invoke(obj, val);
					} else {
						Method formatMethod =  propCls.getMethod("valueOf", String.class);
						setMethod.invoke(obj, formatMethod.invoke(null, val));
					}
				} catch (Exception e) {					
					e.printStackTrace();
				}
			}
		}
		return obj;
	}
	
	/**
	 * @author by K2 Mar 24, 2016
	 *
	 * @desc 判断某对象是否为空..
	 * @param obj
	 * @return
	 */
	protected boolean isNullOrEmpty(Object obj) {
		return Stringer.isNullOrEmpty(obj);
	}

	/**
	 * @author by k2 Apr 13, 2015
	 *
	 * @desc 获取webapp完整URL. e.g http://www.abc.com/app/a/b/c?a=b&c=d...
	 * @param request
	 * @return
	 */
	protected final String getRequestURL(HttpServletRequest request) {

		if (request == null) {
			return "";
		}

		String url = "";
		url = "http://" + request.getServerName() // 服务器地址
		// + ":"
		// + request.getServerPort() //端口号
				+ request.getContextPath() // 项目名称
				+ request.getServletPath(); // 请求页面或其他地址
		try {
			// 参数
			Enumeration<?> names = request.getParameterNames();

			int i = 0;
			String queryString = request.getQueryString();
			if (null != queryString && !"".equals(queryString) && (!queryString.equals("null"))) {
				url = url + "?" + request.getQueryString();
				i++;
			}

			if (names != null) {
				while (names.hasMoreElements()) {
					if (i == 0) {
						url = url + "?";
					}

					String name = (String) names.nextElement();
					if (url.indexOf(name) < 0) {
						url = url + "&";

						String value = request.getParameter(name);
						if (value == null) {
							value = "";
						}
						url = url + name + "=" + value;
						i++;
					}
					// java.net.URLEncoder.encode(url, "ISO-8859");
				}
			}

			// String enUrl = java.net.URLEncoder.encode(url, "utf-8");
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return url;
	}

	/**
	 * @author by k2 Apr 13, 2015
	 *
	 * @desc 从请求中获取参数值
	 * 
	 * @param request
	 * @param parameterName
	 *            -参数名
	 * @param defaultValue
	 *            - 参数值为null时的默认值（int）
	 * @return
	 */
	protected int getParameter(HttpServletRequest request, String parameterName, int defaultValue) {
		String paramVal = request.getParameter(parameterName);
		if (isNullOrEmpty(paramVal)) {
			return defaultValue;
		} else {
			return Integer.parseInt(paramVal);
		}

	}

	/**
	 * @author by k2 Apr 13, 2015
	 *
	 * @desc 从请求中获取参数值
	 * 
	 * @param request
	 * @param parameterName
	 *            -参数名
	 * @param defaultValue
	 *            - 参数值为null时的默认值（Float）
	 * @return
	 */
	protected Float getParameter(HttpServletRequest request, String parameterName, Float defaultValue) {
		String paramVal = request.getParameter(parameterName);
		if (isNullOrEmpty(paramVal)) {
			return defaultValue;
		} else {
			return Float.parseFloat(paramVal);
		}

	}

	/**
	 * @author by k2 Apr 13, 2015
	 *
	 * @desc 从请求中获取参数值
	 * 
	 * @param request
	 * @param parameterName
	 *            -参数名
	 * @param defaultValue
	 *            - 参数值为null时的默认值（Double）
	 * @return
	 */
	protected Double getParameter(HttpServletRequest request, String parameterName, Double defaultValue) {
		String paramVal = request.getParameter(parameterName);
		if (isNullOrEmpty(paramVal)) {
			return defaultValue;
		} else {
			return Double.parseDouble(paramVal);
		}

	}

	/**
	 * @author by k2 Apr 13, 2015
	 *
	 * @desc 从请求中获取参数值
	 * 
	 * @param request
	 * @param parameterName
	 *            -参数名
	 * @param defaultValue
	 *            - 参数值为null时的默认值（Boolean）
	 * @return
	 */
	protected Boolean getParameter(HttpServletRequest request, String parameterName, Boolean defaultValue) {
		String paramVal = request.getParameter(parameterName);
		if (isNullOrEmpty(paramVal)) {
			return defaultValue;
		} else {
			return Boolean.parseBoolean(paramVal);
		}

	}

	/**
	 * @author by k2 Apr 13, 2015
	 *
	 * @desc 从请求中获取参数值
	 * 
	 * @param request
	 * @param parameterName
	 *            -参数名
	 * @param defaultValue
	 *            - 参数值为null时的默认值（String）
	 * @return
	 */
	protected String getParameter(HttpServletRequest request, String parameterName, String defaultValue) {
		String paramVal = request.getParameter(parameterName);
		if (isNullOrEmpty(paramVal)) {
			return null;
		} else {
			return paramVal.trim();
		}

	}

}
